/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package course.providers.jpa;

import course.entities.UserGroup;
import java.io.Serializable;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author def
 */
@Stateless
public class UserGroupProvider implements Serializable {

    private static final long serialVersionUID = 8851638745162105056L;

    @PersistenceContext(unitName = "webPartPU")
    protected EntityManager em;

    public UserGroupProvider() {
    }

    public UserGroup create() {
        UserGroup entity = new UserGroup();
        em.persist(entity);
        return entity;
    }

    public void update(UserGroup entity) {
        em.merge(entity);
    }

    public void delete(UserGroup entity) {
        em.remove(em.merge(entity));
    }

    public UserGroup findById(long id) {
        return (UserGroup) em.find(UserGroup.class, id);
    }

    public UserGroup findByGroupName(String groupName) {
        Query q = em.createQuery("SELECT DISTINCT g FROM UserGroup g WHERE g.groupName = :groupName").setParameter("groupName", groupName);
        if (q.getResultList().isEmpty()) {
            return null;
        }
        UserGroup group = (UserGroup) q.getResultList().get(0);
        return group;
    }

    public UserGroup findGroupByUserId(long userId) {
        Query q = em.createQuery("SELECT ug "
                               + "FROM UserGroup ug JOIN ug.users u "
                               + "WHERE u.id = :userId").setParameter("userId", userId);
        return (UserGroup) q.getSingleResult();
    }

    public List<UserGroup> findAll() {
        Query q = em.createNamedQuery("UserGroup.findAll");
        return (List<UserGroup>) q.getResultList();
    }

}
